﻿using B.MESUI.Login.BasicData_UI.BasicData;
using B.MESUI.Login.BasicData_UI.BasicData.Select;
using B.MESUI.Login.BasicData_UI.Customer;
using B.MESUI.Login.Properties;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace B.MESUI.Login.BasicData_UI.Supplier
{
    public partial class GetSupplierForm : DevExpress.XtraEditors.XtraForm
    {
        private GetUserControl userControl;
        private TextEdit txtCode, txtName;
        private int pageIndex = 1, pageSize = 10, totalCount = 0;
        public FlowLayoutPanel QueryPanel { get; set; }
        public GetSupplierForm()
        {
            InitializeComponent();
            InitLayout();
            userControl = new GetUserControl { Dock = DockStyle.Fill };
            this.Controls.Add(userControl);

            // 指定需要的查询字段和类型
            var fields = new List<GetUserControl.QueryField>
     {
         new GetUserControl.QueryField { FieldName = "SUPPLIER_CODE", DisplayName = "供应商编码", FieldType = GetUserControl.QueryFieldType.TextBox },
         new GetUserControl.QueryField { FieldName = "SUPPLIER_NAME", DisplayName = "供应商名称", FieldType = GetUserControl.QueryFieldType.TextBox },
         new GetUserControl.QueryField { FieldName = "SUPPLIER_ADDRESS", DisplayName = "供应商地址", FieldType = GetUserControl.QueryFieldType.TextBox }
     };
            userControl.SetQueryFields(fields);

            _ = LoadData();
            // 恢复查询和分页按钮事件绑定
            userControl.btnQuery.Click += async (s, e) => { pageIndex = 1; await LoadData(); };
            userControl.btnReset.Click += async (s, e) =>
            {
                var qv = userControl.GetQueryValues();
                foreach (var k in qv.Keys.ToList())
                {
                    if (userControl.QueryControls[k] is DevExpress.XtraEditors.BaseEdit be)
                        be.EditValue = null;
                }
                pageIndex = 1;
                await LoadData();
            };
            userControl.btnPrev.Click += async (s, e) => { if (pageIndex > 1) { pageIndex--; await LoadData(); } };
            userControl.btnNext.Click += async (s, e) => { if (pageIndex < GetTotalPages()) { pageIndex++; await LoadData(); } };
            userControl.btnFirst.Click += async (s, e) => { pageIndex = 1; await LoadData(); };
            userControl.btnLast.Click += async (s, e) => { pageIndex = GetTotalPages(); await LoadData(); };
            userControl.btnJump.Click += async (s, e) =>
            {
                int jumpPage;
                if (int.TryParse(userControl.txtJump.Text, out jumpPage))
                {
                    if (jumpPage >= 1 && jumpPage <= GetTotalPages())
                    {
                        pageIndex = jumpPage;
                        await LoadData();
                    }
                }
            };
            //添加按钮点击事件
            userControl.btnAdd.Click += (s, e) =>
            {
                var addForm =new AddSupplierForm();
                addForm.Supplier_Load += () =>
                {
                    LoadData();
                };
                addForm.ShowDialog();
            };
            //修改按钮点击事件
            userControl.btnEdit.Click += (s, e) =>
            {
                // 获取选中行
                var gridView = userControl.MainGrid.MainView as GridView;
                if (gridView != null && gridView.GetSelectedRows().Length > 0)
                {
                    var selectedRowHandle = gridView.GetSelectedRows()[0];
                    if (selectedRowHandle >= 0)
                    {
                        // 获取选中的客户数据
                        var SupplierDto = gridView.GetRow(selectedRowHandle) as GetSupplierDTO;
                        if (SupplierDto != null)
                        {
                            // 将 CustomerDTO 转换为 UpdateCustomer
                            var updateCustomer = new UpdateSupplierDTO
                            {
                                ID = SupplierDto.ID,
                                supplieR_CODE = SupplierDto.SUPPLIER_CODE,
                                supplieR_NAME = SupplierDto.SUPPLIER_NAME,
                                supplieR_ABBREVIATION = SupplierDto.SUPPLIER_ABBREVIATION,
                                supplieR_PHONE = SupplierDto.SUPPLIER_PHONE,
                                supplieR_ADDRESS = SupplierDto.SUPPLIER_ADDRESS,
                                crediT_CODE = SupplierDto.CREDIT_CODE,
                                supplieR_NODE = SupplierDto.SUPPLIER_NODE
                            };

                            // 创建编辑窗体并传递数据
                            var editForm = new UpdateSupplierForm(updateCustomer);
                            editForm.Supplier_Event += () =>
                            {
                                LoadData();
                            };
                            editForm.ShowDialog();
                        }
                    }
                }
                else
                {
                    XtraMessageBox.Show("请先选择要修改的客户记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            };
            //批量删除
            userControl.btnDelete.Click += async (s, e) =>
            {
                var gridView = userControl.MainGrid.MainView as GridView;
                if (gridView != null)
                {
                    // 获取所有选中的行的ID
                    List<string> selectedIds = new List<string>();

                    // 获取选中的行
                    int[] selectedRows = gridView.GetSelectedRows();
                    if (selectedRows != null && selectedRows.Length > 0)
                    {
                        foreach (int rowHandle in selectedRows)
                        {
                            if (rowHandle >= 0)
                            {
                                var suplierDto = gridView.GetRow(rowHandle) as GetSupplierDTO;
                                if (suplierDto != null)
                                {
                                    selectedIds.Add(suplierDto.ID);
                                }
                            }
                        }
                    }
                    else
                    {
                        // 如果没有通过 GetSelectedRows 获取到选中行，则尝试通过复选框获取
                        for (int i = 0; i < gridView.RowCount; i++)
                        {
                            bool isChecked = false;
                            try
                            {
                                isChecked = Convert.ToBoolean(gridView.GetRowCellValue(i, "CheckboxColumn"));
                            }
                            catch
                            {
                                // 忽略转换错误
                                continue;
                            }

                            if (isChecked)
                            {
                                var suplierDto = gridView.GetRow(i) as GetSupplierDTO;
                                if (suplierDto != null)
                                {
                                    selectedIds.Add(suplierDto.ID);
                                }
                            }
                        }
                    }

                    // 如果没有选中任何行，提示用户
                    if (selectedIds.Count == 0)
                    {
                        XtraMessageBox.Show("请至少选择一条记录进行删除！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    // 确认删除
                    if (XtraMessageBox.Show($"确定要删除选中的 {selectedIds.Count} 条记录吗？", "确认删除",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        try
                        {
                            // 构建请求URL
                            string url = Settings.Default.BaseUrl_SLY + MethodConst.DeleteSupplierList;

                            // 将ID列表转换为逗号分隔的字符串
                            string idsString = string.Join(",", selectedIds);

                            // 添加查询参数
                            url += "?Ids=" + System.Web.HttpUtility.UrlEncode(idsString);

                            // 发送DELETE请求
                            string result = await BaseMethod.MethodsURL("put", url);

                            // 解析返回结果
                            var apiResult = JsonConvert.DeserializeObject<dynamic>(result);

                            // 检查返回码
                            if (apiResult != null && apiResult.code.ToString() == "200")
                            {
                                XtraMessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                LoadData(); // 刷新数据
                            }
                            else
                            {
                                string errorMsg = apiResult?.message?.ToString() ?? "未知错误";
                                XtraMessageBox.Show($"删除失败：{errorMsg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                LoadData(); // 即使失败也刷新数据，确保UI状态正确
                            }
                        }
                        catch (Exception ex)
                        {
                            XtraMessageBox.Show($"删除失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            LoadData(); // 发生异常时也刷新数据
                        }
                    }
                }
            };
            //导出
            userControl.btnExport.Click += (sender, e) =>
            {
                string url = Settings.Default.BaseUrl_SLY + MethodConst.GetSupplierexport;
                using (HttpClient client = new HttpClient())
                {
                    try
                    {
                        var response = client.GetAsync(url).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            var bytes = response.Content.ReadAsByteArrayAsync().Result;
                            using (SaveFileDialog sfd = new SaveFileDialog())
                            {
                                sfd.Filter = "Excel文件|*.xlsx|所有文件|*.*";
                                sfd.FileName = "产线信息导出.xlsx";
                                if (sfd.ShowDialog() == DialogResult.OK)
                                {
                                    System.IO.File.WriteAllBytes(sfd.FileName, bytes);
                                    MessageBox.Show("导出成功！");
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("导出失败！");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("导出异常：" + ex.Message);
                    }
                }

            };
        }
        //显示
        private int GetTotalPages() => (int)Math.Ceiling((double)totalCount / pageSize);
        /// <summary>
        /// 供应商显示
        /// </summary>
        /// <returns></returns>
        private async Task LoadData()
        {
            string url = Settings.Default.BaseUrl_SLY + B.MESUI.Login.BasicData_UI.MethodConst.GetPageSupplier;
            var paramList = new List<string>
            {
                 $"PageIndex={pageIndex}",
                 $"PageSize={pageSize}"
            };
            var queryValues = userControl.GetQueryValues();
            if (queryValues.ContainsKey("SUPPLIER_CODE") && !string.IsNullOrWhiteSpace(queryValues["SUPPLIER_CODE"]?.ToString()))
                paramList.Add($"SUPPLIER_CODE={queryValues["SUPPLIER_CODE"].ToString().Trim()}");
            if (queryValues.ContainsKey("SUPPLIER_NAME") && !string.IsNullOrWhiteSpace(queryValues["SUPPLIER_NAME"]?.ToString()))
                paramList.Add($"SUPPLIER_NAME={queryValues["SUPPLIER_NAME"].ToString().Trim()}");
            if (queryValues.ContainsKey("SUPPLIER_ADDRESS") && !string.IsNullOrWhiteSpace(queryValues["SUPPLIER_ADDRESS"]?.ToString()))
                paramList.Add($"SUPPLIER_ADDRESS={queryValues["SUPPLIER_ADDRESS"].ToString().Trim()}");
            url += "?" + string.Join("&", paramList);

            using (HttpClient client = new HttpClient())
            {
                var resp = await client.GetAsync(url);
                string json = await resp.Content.ReadAsStringAsync();
                var jobj = JObject.Parse(json);
                totalCount = jobj["totalCount"]?.Value<int>() ?? 0;
                var pageList = jobj["pageDatas"] as JArray;
                var dataList = new List<GetSupplierDTO>();
                if (pageList != null)
                {
                    foreach (var item in pageList)
                    {
                        dataList.Add(item.ToObject<GetSupplierDTO>());
                    }
                }
                // 先绑定数据源
                var gridControl = userControl.MainGrid;
                if (gridControl != null)
                {
                    gridControl.DataSource = dataList;
                   
                    var gridView = gridControl.MainView as GridView;
                    if (gridView != null)
                    {
                        // 添加复选框列
                        if (gridView.Columns["CheckboxColumn"] == null)
                        {
                            // 设置选择模式为多选
                            gridView.OptionsSelection.MultiSelect = true;
                            gridView.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;

                            // 添加行点击事件，确保点击行时不会取消其他行的选择
                            gridView.Click += (s, e) =>
                            {
                                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hitInfo = gridView.CalcHitInfo((e as MouseEventArgs).Location);
                                if (hitInfo.InRow && !(hitInfo.Column != null && hitInfo.Column.FieldName == "CheckboxColumn"))
                                {
                                    // 如果点击的是行而不是复选框列，则切换该行的复选框状态
                                    bool currentValue = Convert.ToBoolean(gridView.GetRowCellValue(hitInfo.RowHandle, "CheckboxColumn"));
                                    gridView.SetRowCellValue(hitInfo.RowHandle, "CheckboxColumn", !currentValue);
                                }
                            };
                        }
                        // 设置表头
                        if (gridView.Columns["ID"] != null)
                            gridView.Columns["ID"].Caption = "编号";
                        if (gridView.Columns["SUPPLIER_CODE"] != null)
                            gridView.Columns["SUPPLIER_CODE"].Caption = "供应商编码";
                        if (gridView.Columns["SUPPLIER_NAME"] != null)
                            gridView.Columns["SUPPLIER_NAME"].Caption = "供应商名称";
                        if (gridView.Columns["SUPPLIER_ABBREVIATION"] != null)
                            gridView.Columns["SUPPLIER_ABBREVIATION"].Caption = "供应商简称";
                        if (gridView.Columns["SUPPLIER_PHONE"] != null)
                            gridView.Columns["SUPPLIER_PHONE"].Caption = "供应商联系电话";
                        if (gridView.Columns["SUPPLIER_ADDRESS"] != null)
                            gridView.Columns["SUPPLIER_ADDRESS"].Caption = "供应商地址";
                        if (gridView.Columns["CREDIT_CODE"] != null)
                            gridView.Columns["CREDIT_CODE"].Caption = "供应商信用代码";
                        if (gridView.Columns["SUPPLIER_NODE"] != null)
                            gridView.Columns["SUPPLIER_NODE"].Caption = "供应商备注";
                        if (gridView.Columns["CREATEDUSERNAME"] != null)
                            gridView.Columns["CREATEDUSERNAME"].Caption = "创建人";
                        if (gridView.Columns["CREATETIME"] != null)
                            gridView.Columns["CREATETIME"].Caption = "创建时间";
                        if (gridView.Columns["UPDATEDUSERNAME"] != null)
                            gridView.Columns["UPDATEDUSERNAME"].Caption = "修改人";
                        if (gridView.Columns["UPDATETIME"] != null)
                            gridView.Columns["UPDATETIME"].Caption = "修改时间";
                        // 可继续添加其他字段
                    }
                    // 优化中间表格区显示
                    gridControl.Dock = DockStyle.Fill;
                    gridView.OptionsView.ColumnAutoWidth = false; // 允许自定义列宽
                    gridView.BestFitColumns(); // 自动适应内容宽度
                    foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView.Columns)
                    {
                        col.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; // 表头居中
                        col.AppearanceHeader.Font = new System.Drawing.Font("Tahoma", 10, System.Drawing.FontStyle.Bold); // 表头加粗
                        col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; // 内容居中、

                    }
                    // 显示行号
                    gridView.IndicatorWidth = 40;
                    gridView.CustomDrawRowIndicator += (s, e) =>
                    {
                        if (e.Info.IsRowIndicator && e.RowHandle >= 0)
                        {
                            e.Info.DisplayText = (e.RowHandle + 1).ToString();
                        }
                    };

                }
                //调试
                if (userControl.MainGrid != null)
                    userControl.MainGrid.DataSource = dataList;
                userControl.lblPageInfo.Text = $"第{pageIndex}/{(GetTotalPages() == 0 ? 1 : GetTotalPages())}页 共{totalCount}条";
            }
        }
    }
}